﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace PServiceBus.Core.Runtime {
    /// <summary>
    /// Class for managing performance counter
    /// </summary>
    public class PerfCounter {
        private const string CATEGORY_NAME = "Phoenix Service Bus";
        private Dictionary<string, PerformanceCounter> _counters = new Dictionary<string, PerformanceCounter>();
        /// <summary>
        /// Load a specific performance counter group and specific counter items for the specific group
        /// It will create a new performance counter group if it does not exists
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="counters"></param>
        public void Load(string groupName, Dictionary<string, PerformanceCounterType> counters) {
            groupName = groupName.StartsWith("PServiceBus") ? groupName : "PServiceBus." + groupName;
            if (!PerformanceCounterCategory.Exists(groupName)) {
                var counterGroup = new CounterCreationDataCollection();
                foreach (var counter in counters) {
                    var counterData = new CounterCreationData(counter.Key, counter.Key, counter.Value);
                    counterGroup.Add(counterData);
                }
                PerformanceCounterCategory.Create(groupName, CATEGORY_NAME, PerformanceCounterCategoryType.Unknown, counterGroup);
            }
            foreach (var counter in counters)
                _counters[counter.Key] = new PerformanceCounter(groupName, counter.Key, false);
        }

        /// <summary>
        /// Update the value of the specified performance counter
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void SetValue(string name, long value) {
            if (!_counters.ContainsKey(name)) return;
            _counters[name].RawValue = value;
        }

        /// <summary>
        /// Increment the current value of the specified performance counter based on the specific value
        /// Default value is 1 if value is not passed
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void IncrementValue(string name, long value = 1) {
            if (!_counters.ContainsKey(name)) return;
            _counters[name].IncrementBy(value);
        }
    }
}
